﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mixture.Data
{
    public class Storage
    {
        Dictionary<string, MUser> userStorage = new Dictionary<string, MUser>();

        public MUser LookupUser(string id)
        {
            if (userStorage.ContainsKey(id))
                return userStorage[id];
            else
                return null;
        }

        public void RegistUser(MUser user)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            if (userStorage.ContainsKey(user.Id))
                userStorage[user.Id] = user;
            else
                userStorage.Add(user.Id, user);
        }

        public IEnumerable<string> GetUsers()
        {
            foreach (var k in userStorage.Keys)
            {
                yield return k;
            }
        }

        private object uidResolverLocker = new object();
        List<KeyValuePair<string, ulong>> uidResolverStorage = new List<KeyValuePair<string, ulong>>();

        public bool AddSidUid(string sid, ulong uid)
        {
            lock (uidResolverLocker)
            {
                foreach (var u in uidResolverStorage)
                {
                    if (u.Key == sid)
                    {
                        return false;
                    }
                }
                uidResolverStorage.Add(new KeyValuePair<string, ulong>(sid, uid));
                return true;
            }
        }

        public ulong GetUid(string sid)
        {
            lock (uidResolverLocker)
            {
                foreach (var u in uidResolverStorage)
                {
                    if (u.Key == sid)
                    {
                        return u.Value;
                    }
                }
                return 0;
            }
        }

        public string GetSid(ulong uid)
        {
            lock (uidResolverLocker)
            {
                foreach (var u in uidResolverStorage)
                {
                    if (u.Value == uid)
                    {
                        return u.Key;
                    }
                }
                return null;
            }
        }
    }
}
